<template>
	<view class="box">
		<view class="row">
			<text>手机号</text>
			<input type="text" v-model="phone" maxlength="12"/>
		</view>
		<view class="row">
			<view class="send">
				<button class="captcha" @click="getCode()" size="mini" :disabled="!codeTag">验证码</button>
				<text>{{second}}</text>
			</view>
			<input type="text" v-model="code"  placeholder="- - - -" maxlength="4" />
		</view>
		<view class="row">
			<button type="primary" :disabled="!loginTag"  style="width: 90%;border-radius: 80rpx;margin-top: 50rpx;" @click="Login(phone)">登录</button>
		</view>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				phone:'',
				code:'',		//验证码
				codeTag:false,		//验证码按钮是否可用：true 可用；false 不可用
				loginTag:false,		//登录按钮是否可用：true 可用；false 不可用
				second:'',			//倒计时时间
			}
		},
		watch:{
			// 监听手机号正则
			phone:function(val){
				this.codeTag = /^1[3456789]\d{9}$/.test(val);
			},
			// 监听验证码长度
			code:function(val){
				if(val.length == 4){
					this.loginTag = true
				} else {
					this.loginTag = false
				}
			}
		},
		methods:{
			async getCode(){
				this.codeTag = false;
				var data = {phone:this.phone};
				var result = await this.$http('/api/sms',data).catch(err=>{
					console.log(err);
				})
				// 把验证码存储到本地缓存
				var code=result.data.list.code;
				uni.setStorageSync("code",code);
				console.log(code,'code')
				// 倒计时定时器
				var second = 10;
				this.second = second;
				var timer = setInterval(()=>{
					second --;
					this.second = second;
					if(second == 0){
						clearInterval(timer);
						this.codeTag = true;
						this.second = '';
					}
				},1000)
				
			},
			async Login(){
				//用户输入的code和缓存中的code进行比对
				var localCode=uni.getStorageSync("code");
				if(localCode&&this.code&&localCode==this.code){
					var result = await this.$http('/api/wxlogin',{phone:this.phone}).catch(err=>{
						console.log(err);
					})
					//获取到token，存储到本地缓存
					var UserInfo=result.data.list;
					uni.setStorageSync("UserInfo",UserInfo);
					uni.reLaunch({
						url:"/pages/my/my"
					})
				}else{
					uni.showToast({
						title:'验证码输入有误，请重新输入'
					})
				}
				
			}
		}
	}
</script>

<style>
	/* 导入外部的样式文件 */
	/* @import url("../../common/css/index.css"); */
	.box{
		position: relative;
	}

	.row{
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		margin: 40rpx;
	}
	.send{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.send text:nth-of-type(2){
		color: #00BB00;
	}
	text{
		font-size: 27rpx;
		margin-bottom: 10rpx;
	}
	input{
		border-bottom: 1rpx solid gray;
		height: 65rpx;
	}
	.captcha{
		background: #f60300;
		color: white;
		padding: 0 20rpx;
		margin-left: 0rpx;
		border-radius: 13rpx;
	}
</style>